package com.ddd.domain.model.sales;

import com.ddd.application.event.PayEventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.ws.ServiceMode;
import java.util.Objects;
import java.util.concurrent.BlockingDeque;

/**
 * 销售的领域服务，主要功能销售单据，发送扣除库存事件
 */
@Service
public class SalesService {


    @Resource
    private SalesRepository salesRepository;
    /**
     * applicationEventPublisher
     */
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 销售
     *
     * @param salesEntity
     * @param payStatus   支付状态
     */
    public void sales(SalesEntity salesEntity, boolean payStatus) {
        PayEventService payEventService = null;
        if (payStatus) {
            salesEntity.paySuccess();
            payEventService = new PayEventService(this, true);
        } else {
            salesEntity.payError();
            payEventService = new PayEventService(this, false);
        }
        //支付事件触发，扣除库存，重试支付
        applicationEventPublisher.publishEvent(payEventService);
        //保存订单和详情
        salesRepository.save(salesEntity);
    }

    /**
     * 销售退回
     *
     * @return
     */
    public SalesEntity salesReturn(String orderId) {
        SalesEntity salesentity = salesRepository.findOrderId(orderId);
        if (Objects.isNull(salesentity)) {
            throw new RuntimeException("");
        }
        //复制销售，生成销退单，扣减库存事件

        new SalesEntity(null, salesentity.get)

        return salesentity;
    }


}
